<?php
/*
 module:		会员管理控制器
 create_time:	2022-08-19 17:06:02
 author:		
 contact:		
*/

namespace app\admin\controller;
use app\admin\model\Member as MemberModel;
use app\common\model\MemberCurrency as MemberCurrencyModel;
use think\exception\ValidateException;
use app\admin\model\Member as MembeModel;
use think\facade\Db;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use app\common\model\UserMoneyLog as UserMoneyLogModel;
use app\admin\model\MemberLevel as MemberLevelModel;
use app\admin\model\AccountAddress as AccountAddressModel;
use app\admin\model\MemberArithmeticalPower as MemberArithmeticalPowerModel;
use app\common\model\MemberPledge as MemberPledgeModel;

class Member extends Admin {

    /*
     * @Description  数据列表
     */
    function index(){
        if (!$this->request->isPost()){
            $level = MemberLevelModel::getMemberList();

            return view('index',['level'=>json_encode($level)]);
        }else{
            $limit  = $this->request->post('limit', 20, 'intval');
            $page = $this->request->post('page', 1, 'intval');

            $where = [];
            $where['id'] = $this->request->post('id', '', 'serach_in');
            $username = $this->request->post('username', '', 'serach_in');
            $where['status'] = $this->request->post('status', '', 'serach_in');
            $where['level_id'] = $this->request->post('level_id', '', 'serach_in');

            if(!empty($username)){
                $member = MemberModel::address($username);
                if($member){
                    $member = $member->toArray();
                    $where['id|pid'] = $member['id'];
                }
            }

            $create_time = $this->request->post('create_time', '', 'serach_in');
            $where['create_time'] = ['between',[strtotime($create_time[0]),strtotime($create_time[1])]];

            $order  = $this->request->post('order', '', 'serach_in');	//排序字段
            $sort  = $this->request->post('sort', '', 'serach_in');		//排序方式

            $orderby = ($sort && $order) ? $sort.' '.$order : 'id desc';

            $res = MemberModel::where(formatWhere($where))->order($orderby)->paginate(['list_rows'=>$limit,'page'=>$page])->toArray();

            foreach ($res['data'] as $k => $v){
                $res['data'][$k]['pmember'] = '';
                //查询上级用户
                if(!empty($v['pid'])){
                    $pmember = MemberModel::getDetails($v['pid']);
                    $res['data'][$k]['pmember'] = $v['pid'].' | '.$pmember['username'];
                }
                $level = MemberLevelModel::getDetails($v['level_id']);
                $res['data'][$k]['level_name'] = $level['name'];

                //获取余额
                $waller = MemberCurrencyModel::member_renew($v['id']);
                $res['data'][$k]['USDT'] = 0;
                $res['data'][$k]['BABM'] = 0;
                $res['data'][$k]['waller'] = $waller;
                foreach ($waller['waller'] as $vw){
                    $res['data'][$k][$vw['name']] = $vw['money'];
                }

                $pledge = MemberPledgeModel::memberPledge($v['id']);
                $res['data'][$k]['pledge'] = $pledge['money'];
                $res['data'][$k]['release_pledge'] = $pledge['release'];
            }

            $data['status'] = 200;
            $data['data'] = $res;
            return json($data);
        }
    }


	/*
 	* @Description  修改排序开关
 	*/
	function updateExt(){
		$postField = 'id,status';
		$data = $this->request->only(explode(',',$postField),'post',null);
		if(!$data['id']) throw new ValidateException ('参数错误');
		MembeModel::update($data);
		return json(['status'=>200,'msg'=>'操作成功']);
	}

	/*
 	* @Description  添加
 	*/
	public function add(){
		$postField = 'username,pic,pid,password,amount,status,create_time';
		$data = $this->request->only(explode(',',$postField),'post',null);

		$this->validate($data,\app\admin\validate\Membe::class);

		$data['password'] = md5($data['password'].config('my.password_secrect'));
		$data['create_time'] = time();

		try{
			$res = MembeModel::insertGetId($data);
		}catch(\Exception $e){
			throw new ValidateException($e->getMessage());
		}
		return json(['status'=>200,'data'=>$res,'msg'=>'添加成功']);
	}


	/*
 	* @Description  修改
 	*/
	public function update(){
		$postField = 'id,username,level_id,deduct_recommended';
		$data = $this->request->only(explode(',',$postField),'post',null);

		$this->validate($data,\app\admin\validate\Membe::class);

		$level = MemberLevelModel::getDetails($data['level_id']);
		if(empty($level)) throw new ValidateException ('没有该等级！');

        $data['create_time'] = strtotime($data['create_time']);

		try{
			MembeModel::where('id',$data['id'])->update($data);
		}catch(\Exception $e){
			throw new ValidateException($e->getMessage());
		}
		return json(['status'=>200,'msg'=>'修改成功']);
	}


	/*
 	* @Description  修改信息之前查询信息的 勿要删除
 	*/
	function getUpdateInfo(){
        $id =  $this->request->post('id', '', 'serach_in');
		if(!$id) throw new ValidateException ('参数错误');
		$field = 'id,username,pid,position,level_id,deduct_recommended';
		$res = MembeModel::where('id',$id)->field($field)->find();
		return json(['status'=>200,'data'=>$res]);
	}


	/*
 	* @Description  删除
 	*/
	function delete(){
		$idx =  $this->request->post('id', '', 'serach_in');
		if(!$idx) throw new ValidateException ('参数错误');
		MembeModel::destroy(['id'=>explode(',',$idx)],true);
		return json(['status'=>200,'msg'=>'操作成功']);
	}


	/*
 	* @Description  查看详情
 	*/
	function detail(){
		$id =  $this->request->post('id', '', 'serach_in');
		if(!$id) throw new ValidateException ('参数错误');
		$field = 'id,username,pic,mobile,amount,status,create_time';
		$res = MembeModel::field($field)->find($id);
		return json(['status'=>200,'data'=>$res]);
	}


	/*
 	* @Description  重置密码
 	*/
	public function resetPwd(){
		$postField = 'id,password';
		$data = $this->request->only(explode(',',$postField),'post',null);
		if(empty($data['id'])) throw new ValidateException ('参数错误');
		if(empty($data['password'])) throw new ValidateException ('密码不能为空');

		$data['password'] = md5($data['password'].config('my.password_secrect'));
		$res = MembeModel::update($data);
		return json(['status'=>200,'msg'=>'操作成功']);
	}


    /**
     * 更新余额
     * @return \think\response\Json
     */
	public function jia(){
		$postField = 'uid,vals';
		$data = $this->request->only(explode(',',$postField),'post',null);

        foreach ($data['vals'] as $v){
            if($v['money'] > 0){
                UserMoneyLogModel::change($data['uid'],$v['name'],$v['money'],'system_operation');
            }
        }

		return json(['status'=>200,'msg'=>'更新成功']);
	}


	/*
 	* @Description  导入
 	*/
	public function importData(){
		$data = $this->request->post();
		$list = [];
		foreach($data as $key=>$val){
			$list[$key]['username'] = $val['用户名'];
			$list[$key]['pic'] = $val['头像'];
			$list[$key]['mobile'] = $val['手机号'];
			$list[$key]['password'] = $val['密码'] ? md5($val['密码']) : '';
			$list[$key]['amount'] = $val['积分'];
			$list[$key]['status'] = getValByKey($val['状态'],'[{"key":"开启","val":"1"},{"key":"关闭","val":"0"}]');
			$list[$key]['create_time'] = time();
		}
		(new MembeModel)->insertAll($list);
		return json(['status'=>200]);
	}

    /**
     * 导出用户
     * @return \think\response\Json|void
     * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception
     * @throws \think\db\exception\DbException
     */
	function dumpdata(){
		$page = $this->request->param('page', 1, 'intval');
		$limit = config('my.dumpsize') ? config('my.dumpsize') : 1000;

		$state = $this->request->param('state');

        $where = [];
        $where['id'] = $this->request->post('id', '', 'serach_in');
        $username = $this->request->post('username', '', 'serach_in');
        $where['status'] = $this->request->post('status', '', 'serach_in');
        $where['level_id'] = $this->request->post('level_id', '', 'serach_in');

        if(!empty($username)){
            $member = MembeModel::address($username);
            if($member){
                $member = $member->toArray();
                $where['id|pid'] = $member['id'];
            }
        }

        $create_time = $this->request->post('create_time', '', 'serach_in');
        $where['create_time'] = ['between',[strtotime($create_time[0]),strtotime($create_time[1])]];

        $field = 'id,pid,username,pic,level_id,invitation,usdt,lcc,adc,dividend,reward,position,mnemonic,amount,status,create_time';

        $order  = $this->request->post('order', '', 'serach_in');	//排序字段
        $sort  = $this->request->post('sort', '', 'serach_in');		//排序方式

        $orderby = ($sort && $order) ? $sort.' '.$order : 'id desc';

        $res = MembeModel::where(formatWhere($where))->field($field)->order($orderby)->paginate(['list_rows'=>$limit,'page'=>$page])->toArray();

        foreach ($res['data'] as $k => $v){
            $res['data'][$k]['pmember'] = '';
            //查询上级用户
            if(!empty($v['pid'])){
                $pmember = MembeModel::getDetails($v['pid']);
                $res['data'][$k]['pmember'] = $pmember['username'];
            }
            $level = \app\common\model\MemberLevel::getDetails($v['level_id']);
            $res['data'][$k]['level_name'] = $level['name'];
        }

		$cache_key = 'Membe';
		if($page == 1){
			cache($cache_key,null);
			cache($cache_key,[]);
		}
		if($res['data']){
			cache($cache_key,array_merge(cache($cache_key),$res['data']));
			$data['percentage'] = ceil($page * 100/ceil($res['total']/$limit));
			$data['state'] =  'ok';
			return json($data);
		}
		if($state == 'ok'){
			$spreadsheet = new Spreadsheet();
			$sheet = $spreadsheet->getActiveSheet();

			$sheet->setCellValue('A1','编号');
			$sheet->setCellValue('B1','用户名');
			$sheet->setCellValue('C1','上级用户');
			$sheet->setCellValue('D1','邀请码');
			$sheet->setCellValue('E1','用户等级');
			$sheet->setCellValue('F1','USDT');
            $sheet->setCellValue('G1','ADC');
//			$sheet->setCellValue('G1','MMST');
//			$sheet->setCellValue('H1','分红点');
//            $sheet->setCellValue('I1','奖励点');
//            $sheet->setCellValue('H1','所在位置');
            $sheet->setCellValue('H1','创建时间');

			foreach(cache($cache_key) as $k=>$v){
				$sheet->setCellValue('A'.($k+2),$v['id']);
				$sheet->setCellValue('B'.($k+2),$v['username']);
				$sheet->setCellValue('C'.($k+2),$v['pmember']);
				$sheet->setCellValue('D'.($k+2),$v['invitation']);
				$sheet->setCellValue('E'.($k+2),$v['level_name']);
                $sheet->setCellValue('F'.($k+2),$v['usdt']);
                $sheet->setCellValue('G'.($k+2),$v['adc']);
//                $sheet->setCellValue('G'.($k+2),$v['lcc']);
//                $sheet->setCellValue('H'.($k+2),$v['dividend']);
//                $sheet->setCellValue('I'.($k+2),$v['reward']);
//                $sheet->setCellValue('J'.($k+2),$v['position']);
                $sheet->setCellValue('H'.($k+2),date('Y-m-d H:i:s',$v['create_time']));
			}

			$filename = '会员管理.'.config('my.dump_extension');
			header('Content-Type: application/vnd.ms-excel');
			header('Content-Disposition: attachment;filename='.$filename);
 			header('Cache-Control: max-age=0');
			$writer = new Xlsx($spreadsheet);
			$writer->save('php://output');exit;
		}
	}


	/*
 	* @Description  禁用
 	*/
	public function forbidden(){
		$idx = $this->request->post('id', '', 'serach_in');
		if(empty($idx)) throw new ValidateException ('参数错误');

		$data['status'] = 0;
		$res = MembeModel::where(['id'=>explode(',',$idx)])->update($data);
		return json(['status'=>200,'msg'=>'操作成功']);
	}


	/*
 	* @Description  启用
 	*/
	public function start(){
		$idx = $this->request->post('id', '', 'serach_in');
		if(empty($idx)) throw new ValidateException ('参数错误');

		$data['status'] = 1;
		$res = MembeModel::where(['id'=>explode(',',$idx)])->update($data);
		return json(['status'=>200,'msg'=>'操作成功']);
	}

    /**
     * 矩阵关系图
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function diagram(){
        $id = 1;
        if ($this->request->isPost()){
            $id = $this->request->post('id', '', 'serach_in');
        }
        $member = MembeModel::getDetails($id);

        //查询用户等级
        $level_list = MemberLevelModel::getMemberList();
        $level = [];
        foreach ($level_list as $v){
            $level[$v['id']] = $v;
            if($v['level'] == 0) $level[0] = $v;
        }

        //查询整个矩阵图
        $list = MembeModel::member_matrix($member['position'],$level);

        return view('diagram',['list'=>json_encode($list)]);
    }

    /**
     * 推荐关系图
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function recommend(){
        $id = 1;
        if ($this->request->isPost()){
            $id = $this->request->post('id', '', 'serach_in');
        }
        $member = MembeModel::getDetails($id);
        //查询用户等级
        $level_list = MemberLevelModel::getMemberList();
        $level = [];
        foreach ($level_list as $v){
            $level[$v['id']] = $v;
            if($v['level'] == 0) $level[0] = $v;
        }

        $list = [
            'name'  =>  $id.' | 等级:'.$level[$member['level_id']]['name'],
            'parent'    => null,
            'children'  =>  []
        ];

        //查询整个矩阵图
        $list['children'] = MembeModel::member_diagram($id,$level);

        return view('recommend',['list'=>json_encode($list)]);
    }

}

